﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Web.Security;


using System.Text.RegularExpressions;
using System.IO;


using CooWork.Models;
using CooWork.Services;
using CooWork.Core;
using Coowork.Data.Mapping;

namespace CooWork.Controllers
{
    public class FileController : BaseController
    {
        //
        // GET: /File/
        private CooWorkEntities context = new CooWorkEntities();
        private readonly IMessage ims;
        private readonly IRawjson irj;
        private readonly ICompareDiff icd;
        private readonly ITaskActionLog ital;

        public FileController(IMessage imessage,IRawjson irawjson,ICompareDiff icomparediff,ITaskActionLog iTaskActionLog)
        {
            this.ims = imessage;
            this.irj = irawjson;
            this.icd = icomparediff;
            this.ital = iTaskActionLog;
        }


        [HttpPost]
        public JsonResult JEdit(Attachment ath)
        {

            Attachment ath2 = context.Attachments.Single(x => x.ID == ath.ID);
            icd.CopyNonNullProperties(ath, ath2);


            if (ModelState.IsValid)
            {
                context.Entry(ath2).State = EntityState.Modified;
                context.SaveChanges();
            }
            else
            {
                return new JsonNetResult { Data = ModelState.Select(x => x.Value.Errors).Where(x => x.Count > 0).ToList() };
            }

            var result = new JsonNetResult
            {
                Data = ath2,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Settings = { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }
            };
            return result;

        }

        [HttpPost]
        public JsonResult JDel(Attachment att)
        {
            Attachment att2 = context.Attachments.Single(x => x.ID == att.ID);

            ital.LogAction(CacheSet.U2N(UserService.Ugid()) + " 删除附件 ["+att2.Filename+"]", att2.TaskId.Value, (int?)null);            
            System.IO.File.Delete(Server.MapPath("/upload/" + att2.FilePath));
            context.Attachments.Remove(att2);
            context.SaveChanges();

        


            var result = new JsonNetResult
            {
                Data = true,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Settings = { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }
            };
            return result;
        }



        [HttpPost]      
        public JsonResult JCreate(string auth,string user)
        {

            var id = StringCipher.Decrypt(auth, user);
            if (Regex.Match(id, @"^\d+_([\S]+)").Groups[1].Value != user)
            {
                return new JsonResult { Data = false };
            }

            var ucid =z.GetZInt(Regex.Match(id, @"^(\d+)_").Groups[1].Value);
            var Files = Request.Files;
            var arr1 = Files.AllKeys;
            if (Files.AllKeys.Count() == 0)
                return new JsonResult();

            System.Guid gid = Guid.NewGuid();
            Attachment ath = new Attachment();
            ath.cid = ucid;
            string path = ath.cid + "/" + DateTime.Now.ToString("yyyyMMdd") + "/";
            ath.ContentSize = Files[0].ContentLength;
            ath.ContentType = Files[0].ContentType;
            ath.Filename = Files[0].FileName;
            ath.TaskId = z.GetZInt(Request.QueryString["taskId"]);
            ath.UploadDate = DateTime.Now;
            ath.UserId = new Guid(user);
            ath.FilePath = path + gid.ToString() + Path.GetExtension(ath.Filename);
            if (!Directory.Exists(Server.MapPath("/upload/") + path))
            {
                Directory.CreateDirectory(Server.MapPath("/upload/") + path);
            }
            Files[0].SaveAs(Server.MapPath("/upload/") + ath.FilePath);

            context.Attachments.Add(ath);
            context.SaveChanges();


            var UserId = CacheSet.U2N(ucid, ath.UserId.Value);
            var Filedesc = string.IsNullOrWhiteSpace(ath.Filedesc) ? "添加描述" : ath.Filedesc;
            var ContentSize=z.ContentSize((double)ath.ContentSize.Value);


            ital.LogAction(CacheSet.U2N(ath.cid.Value,new Guid(user)) +" 添加附件 ["+ath.Filename+"]", ath.TaskId.Value, (int?)null,ath.cid.Value,new Guid(user));



            var result = new JsonNetResult
            {
                Data = new {ath.ID,ContentSize,ath.Filename,ath.FilePath,ath.UploadDate,UserId,Filedesc },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Settings = { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }
            };
            return result;
        }





        public ActionResult Index()
        {
            return View();
        }

    }
}
